import { ref, reactive, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance, TablePaginationConfig } from 'ant-design-vue'
import {
  getNotificationList,
  markNotificationRead,
  markNotificationsRead,
  markAllNotificationsRead,
  clearReadNotifications,
  createNotification,
  deleteNotifications
} from '@/api/notification'
import { 
  NotificationType, 
  NotificationStatus, 
  NotificationLevel 
} from '@/types/api/notification'
import type { 
  Notification, 
  NotificationQuery, 
  CreateNotification
} from '@/types/api/notification'
import { useI18n } from 'vue-i18n'

/**
 * 通知管理的钩子函数
 */
export default function useNotificationManagement() {
  // ------------ 国际化和工具引入 ------------
  const { t } = useI18n()
  
  // ------------ 加载状态 ------------
  const loading = ref(false)
  const submitLoading = ref(false)
  
  // ------------ 组件引用 ------------
  const formRef = ref<FormInstance>()
  
  // ------------ 数据列表 ------------
  const notificationList = ref<Notification[]>([])
  
  // ------------ 选中行数据 ------------
  const selectedRowKeys = ref<string[]>([])
  
  // ------------ 弹窗状态 ------------
  const detailVisible = ref(false)
  const formVisible = ref(false)
  
  // ------------ 当前通知详情 ------------
  const currentNotification = ref<Partial<Notification>>({})
  
  // ------------ 日期范围 ------------
  const dateRange = ref<[string, string] | undefined>(undefined)
  
  // ------------ 查询参数 ------------
  const queryParams = reactive<NotificationQuery>({
    title: '',
    type: undefined,
    status: undefined,
    level: undefined,
    page: 1,
    pageSize: 10
  })
  
  // ------------ 分页配置 ------------
  const pagination = reactive<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => t('common.totalItems', { total })
  })
  
  // ------------ 通知表单数据 ------------
  const form = reactive<Partial<CreateNotification>>({
    title: '',
    content: '',
    type: NotificationType.SYSTEM,
    level: NotificationLevel.NORMAL,
    targetUserId: '',
    link: ''
  })
  
  // ------------ 错误处理状态 ------------
  const loadError = ref(false)
  const errorMessage = ref('')
  
  // ------------ 表格选择变更 ------------
  const onSelectChange = (keys: string[]) => {
    selectedRowKeys.value = keys
  }
  
  // ------------ 表格分页变更 ------------
  const handleTableChange = (pag: TablePaginationConfig) => {
    pagination.current = (pag.current ?? 1) as number
    pagination.pageSize = (pag.pageSize ?? 10) as number
    fetchNotificationList()
  }
  
  // ------------ 搜索 ------------
  const handleSearch = () => {
    pagination.current = 1
    fetchNotificationList()
  }
  
  // ------------ 重置搜索条件 ------------
  const resetQuery = () => {
    queryParams.title = ''
    queryParams.type = undefined
    queryParams.status = undefined
    queryParams.level = undefined
    dateRange.value = undefined
    pagination.current = 1
    fetchNotificationList()
  }
  
  // ------------ 获取通知列表 ------------
  const fetchNotificationList = async () => {
    loading.value = true
    loadError.value = false
    errorMessage.value = ''
    
    try {
      // 处理日期范围
      const params = { ...queryParams }
      params.page = pagination.current ?? 1
      params.pageSize = pagination.pageSize ?? 10
      
      if (dateRange.value) {
        params.dateRange = dateRange.value
      }
      
      const res = await getNotificationList(params)
      if (res.success) {
        notificationList.value = res.data.list
        pagination.total = res.data.total
      } else {
        errorMessage.value = res.message || t('notification.loadFailed')
        loadError.value = true
      }
    } catch (error: any) {
      errorMessage.value = error?.message || t('notification.loadFailed')
      loadError.value = true
    } finally {
      loading.value = false
    }
  }
  
  // ------------ 查看通知详情 ------------
  const handleView = async (record: Notification) => {
    try {
      currentNotification.value = record
      detailVisible.value = true
      
      // 如果是未读通知，标记为已读
      if (record.status === NotificationStatus.UNREAD) {
        await markNotificationRead(record.id)
        fetchNotificationList()
      }
    } catch (error) {
      message.error(t('notification.markReadFailed'))
    }
  }
  
  // ------------ 标记为已读 ------------
  const handleMarkRead = async (record: Notification) => {
    try {
      const res = await markNotificationRead(record.id)
      if (res.success) {
        message.success(t('notification.markReadSuccess'))
        fetchNotificationList()
      } else {
        message.error(res.message || t('notification.markReadFailed'))
      }
    } catch (error) {
      message.error(t('notification.markReadFailed'))
    }
  }
  
  // ------------ 批量标记已读 ------------
  const handleBatchRead = async () => {
    if (selectedRowKeys.value.length === 0) {
      message.warning(t('common.noSelection'))
      return
    }
    
    try {
      const res = await markNotificationsRead(selectedRowKeys.value)
      if (res.success) {
        message.success(t('notification.batchMarkReadSuccess'))
        selectedRowKeys.value = []
        fetchNotificationList()
      } else {
        message.error(res.message || t('notification.batchMarkReadFailed'))
      }
    } catch (error) {
      message.error(t('notification.batchMarkReadFailed'))
    }
  }
  
  // ------------ 全部标记已读 ------------
  const handleMarkAllRead = async () => {
    try {
      const res = await markAllNotificationsRead()
      if (res.success) {
        message.success(t('notification.markAllReadSuccess'))
        selectedRowKeys.value = []
        fetchNotificationList()
      } else {
        message.error(res.message || t('notification.markAllReadFailed'))
      }
    } catch (error) {
      message.error(t('notification.markAllReadFailed'))
    }
  }
  
  // ------------ 清空已读通知 ------------
  const handleClearRead = async () => {
    try {
      const res = await clearReadNotifications()
      if (res.success) {
        message.success(t('notification.clearReadSuccess'))
        selectedRowKeys.value = []
        fetchNotificationList()
      } else {
        message.error(res.message || t('notification.clearReadFailed'))
      }
    } catch (error) {
      message.error(t('notification.clearReadFailed'))
    }
  }
  
  // ------------ 删除通知 ------------
  const handleDelete = async (record: Notification) => {
    try {
      const res = await deleteNotifications([record.id])
      if (res.success) {
        message.success(t('notification.deleteSuccess'))
        // 处理边界情况，当删除后页面无数据时跳转到前一页
        if (pagination.current && pagination.current > 1 && notificationList.value.length === 1) {
          pagination.current -= 1
        }
        fetchNotificationList()
      } else {
        message.error(res.message || t('notification.deleteFailed'))
      }
    } catch (error) {
      message.error(t('notification.deleteFailed'))
    }
  }
  
  // ------------ 批量删除通知 ------------
  const handleBatchDelete = async () => {
    if (selectedRowKeys.value.length === 0) {
      message.warning(t('common.noSelection'))
      return
    }
    
    try {
      const res = await deleteNotifications(selectedRowKeys.value)
      if (res.success) {
        message.success(t('notification.batchDeleteSuccess'))
        selectedRowKeys.value = []
        // 处理边界情况，当删除后页面无数据时跳转到前一页
        if (pagination.current && pagination.current > 1 && notificationList.value.length === selectedRowKeys.value.length) {
          pagination.current -= 1
        }
        fetchNotificationList()
      } else {
        message.error(res.message || t('notification.batchDeleteFailed'))
      }
    } catch (error) {
      message.error(t('notification.batchDeleteFailed'))
    }
  }
  
  // ------------ 添加通知 ------------
  const handleAdd = () => {
    resetForm()
    formVisible.value = true
  }
  
  // ------------ 提交表单 ------------
  const handleSubmit = async () => {
    try {
      // 表单验证
      await formRef.value?.validate()
      
      submitLoading.value = true
      
      const res = await createNotification(form as CreateNotification)
      if (res.success) {
        message.success(t('notification.sendSuccess'))
        formVisible.value = false
        fetchNotificationList()
      } else {
        message.error(res.message || t('notification.sendFailed'))
      }
    } catch (error) {
      console.error('发送通知失败:', error)
    } finally {
      submitLoading.value = false
    }
  }
  
  // ------------ 重置表单 ------------
  const resetForm = () => {
    form.title = ''
    form.content = ''
    form.type = NotificationType.SYSTEM
    form.level = NotificationLevel.NORMAL
    form.targetUserId = ''
    form.link = ''
    
    // 重置表单验证状态
    formRef.value?.resetFields()
  }
  
  // ------------ 日期格式化 ------------
  const formatDate = (date: string | undefined) => {
    return date ? new Date(date).toLocaleString() : ''
  }
  
  // ------------ 监听弹窗关闭 ------------
  watch(formVisible, (val) => {
    if (!val) {
      resetForm()
    }
  })
  
  // ------------ 初始化 ------------
  onMounted(() => {
    fetchNotificationList()
  })
  
  return {
    // 状态
    loading,
    submitLoading,
    notificationList,
    selectedRowKeys,
    pagination,
    queryParams,
    dateRange,
    detailVisible,
    formVisible,
    formRef,
    form,
    currentNotification,
    loadError,
    errorMessage,
    
    // 方法
    onSelectChange,
    handleTableChange,
    handleSearch,
    resetQuery,
    fetchNotificationList,
    handleView,
    handleMarkRead,
    handleBatchRead,
    handleMarkAllRead,
    handleClearRead,
    handleDelete,
    handleBatchDelete,
    handleAdd,
    handleSubmit,
    resetForm,
    formatDate
  }
} 